package com.joker.microstoremanager.service;

import com.google.common.base.Strings;
import com.joker.microstoremanager.model.MicroShop;
import com.joker.microstoremanager.model.Tag;
import com.joker.microstoremanager.repository.GoodsTagRepository;
import com.joker.microstoremanager.repository.TagRepository;
import com.joker.microstoremanager.service.base.BaseService;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;

@Service
public class TagService extends BaseService<Tag, Long> {

    @Resource
    private TagRepository tagRepository;
    @Resource
    private GoodsTagRepository goodsTagRepository;

    @Resource
    public void setRepository(TagRepository repository) {
        this.repository = repository;
    }

    public Tag findByShopIdAndName(Long shopId, String name) {
        return tagRepository.findByShopIdAndName(shopId, name);
    }

    public Page<Tag> findByShopIdAndName(Long id, String tagName, Pageable request) {
        Tag tag = new Tag();
        tag.setName(Strings.emptyToNull(tagName));
        MicroShop shop = new MicroShop();
        shop.setId(id);
        tag.setShop(shop);
        Example<Tag> example = Example.of(tag);
        return tagRepository.findAll(example, request);
    }

    @Transactional
    public void deleteById(Long id) {
        goodsTagRepository.deleteByTagId(id);
        tagRepository.delete(id);
    }
}
